package com.roncoo.example.controller;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.*;

@Controller
@RequestMapping("/web")
public class WebController {

    @Autowired
    RestTemplate restTemplate;

    private static final Logger logger = LoggerFactory.getLogger(WebController.class);

    @RequestMapping("index")
    public String index(ModelMap map) {
        logger.info("这里是controller");
        map.put("title", "hello world");
        return "index"; // 注意，不要在最前面加上/，linux下面会出错
    }

    @PostMapping("saveRtspUrl")
    public @ResponseBody String saveRtspUrl(@RequestBody Map map) {

        String l1 = (String) map.get("liu1");
        String l2 = (String) map.get("liu2");
        String liuName = (String) map.get("liu2Name");
        if (null != l2 && null != l1) {
            String url = "classpath:application.properties";
            //rtsp://rtspstream:c68fb2acfe88a6d098c70a2083724f7a@zephyr.rtsp.stream/movie
            FileInputStream fileInputStream = null;
            FileOutputStream fos = null;
            try {
                Map<String, String> sendMap = new HashMap<>(2);
                sendMap.put("rtsp_in", l1);
                sendMap.put("rtsp_out", l2);
                String ip = getIpFromStr(l2);
                if (!ObjectUtils.isEmpty(l2)) {
                    try {
                        String path = "http://" + ip + ":3939/pipe";
                        HttpHeaders headers = new HttpHeaders();
                        headers.setContentType(MediaType.APPLICATION_JSON);
                        HttpEntity request1 = new HttpEntity<>(JSON.toJSONString(sendMap), headers);
                        System.out.println("请求下游系统，请求url为"+path+",请求参数为"+JSON.toJSONString(sendMap)+";请求类型POST");
                        ResponseEntity<String> result = restTemplate.postForEntity(path, request1, String.class);
                        System.out.println("请求返回结果信息"+result);
                    } catch (RestClientException e) {
                        System.out.println("请求失败，原因"+e.getMessage());
                        //throw new RuntimeException(e);
                    }
                }

                //修改配置文件
                File file = ResourceUtils.getFile(url);
                String parentFilePath = file.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getPath();
                parentFilePath = parentFilePath + "\\monitor-rtsp-hls\\";
                String confFile = parentFilePath + "conf\\monitor.properties";
                String cmdFile = parentFilePath + "start.bat";
                Properties props = new Properties();
                fileInputStream = new FileInputStream(confFile);
                props.load(fileInputStream);
                //props.remove("monitor.dev1.stream_url");
                props.setProperty("monitor.dev1.stream_url", l2);
                if (!ObjectUtils.isEmpty(liuName)) {
                    props.setProperty("monitor.dev1.title", liuName);
                }
                fos = new FileOutputStream(confFile);
                props.store(fos, null);
                Thread.sleep(100);
                //打开cmd窗口进行流播放
                //启用cmd运行IE的方式来打开网址。
                cmdFile.replace("\\", "/");
                String str = "cmd /c start   " + cmdFile;

                Runtime.getRuntime().exec(str);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return "success";
    }

    public String getIpFromStr(String str) {
        Pattern pattern = compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            return matcher.group();
        } else {
            return null;
        }
    }

    @PostMapping("closeRtspUrl")
    public @ResponseBody String closeRtsp(@RequestBody Map map) {


        String url = "classpath:application.properties";
        //rtsp://rtspstream:c68fb2acfe88a6d098c70a2083724f7a@zephyr.rtsp.stream/movie
        FileInputStream fileInputStream = null;
        FileOutputStream fos = null;
        try {
            File file = ResourceUtils.getFile(url);
            String parentFilePath = file.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getPath();
            String cmdFile = parentFilePath + File.separator + "monitor-rtsp-hls" + File.separator + "stop.bat";

            //启用cmd运行IE的方式来打开网址。
            cmdFile.replace("\\", "/");
            String str = "cmd /c start   " + cmdFile;
//
            Runtime.getRuntime().exec(str);


        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return "success";
    }

    @RequestMapping("error")
    public String error(ModelMap map) {
        throw new RuntimeException("测试异常");
    }

}
